import axios from 'axios'
import { ElMessage } from 'element-plus'
import cookies from './cookies'

// create an axios instance
const service = axios.create({
  timeout: 80000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config: any) => {
    const token: string | undefined = cookies.get('VX-Token')
    if (token) {
      config.headers['VX-Token'] = token
      config.headers.Authorization = +token
    }
    return config
  },
  (error: any) => {
    console.log('出错啦', error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response: any) => {
    return response.data
  },
  (error: any) => {
    console.log('err' + error) // for debug
    ElMessage.error('服务器请求错误，请稍后再试')
    return Promise.reject(error)
  }
)

// assemble request
const request = (options: any, baseURL: string): Promise<any> => {
  // 合并baseURL到options中
  return service({ ...options, baseURL })
    .then((res) => res)
    .catch((error) => {
      throw error
    }) as Promise<any>
}

export const requestVXBoss = (options: any) => {
  return request(options, import.meta.env.VITE_VX_BOSS_API_PREFIX)
}

export const requestZhipin = (options: any) => {
  return request(options, import.meta.env.VITE_ZHIPIN_WAPI_PREFIX)
}
